package middleware

import (
	"github.com/gin-gonic/gin"
	"mall-go/common"
	"mall-go/model"
	"net/http"
	"strings"
)

//这里的中间件可能会存在性能问题，因为每次拿到token都去数据库进行查询了，后面可以使用redis进行优化

// MallAuthMiddleware 商城用户中间件
func MallAuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 获取Authorization handler
		tokenstring := context.GetHeader("Authorization")

		//验证格式
		if tokenstring == "" || !strings.HasPrefix(tokenstring, "Bearer ") {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token格式不正确！",
			})
			context.Abort() //将这次请求抛弃
			return
		}

		//如果验证通过，提取token
		tokenstring = tokenstring[7:]

		token, claims, err := common.ParseToken(tokenstring)

		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token无效或解析token错误！",
			})
			context.Abort() //将这次请求抛弃
			return
		}

		//验证通过获取claims中的userid
		userId := claims.UserId
		DB := common.GetDB()
		var user model.MallUser
		DB.First(&user, userId)

		//验证用户
		if user.UserID == 0 {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "用户不存在！",
			})
			context.Abort() //将这次请求抛弃
			return
		}

		//用户存在将user信息写入上下文
		context.Set("mallUser", user)
		context.Next()
	}
}

// AdminAuthMiddleware 后台中间件
func AdminAuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 获取Authorization handler
		tokenstring := context.GetHeader("Authorization")

		//验证格式
		if tokenstring == "" || !strings.HasPrefix(tokenstring, "Bearer ") {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token格式不正确！",
			})
			context.Abort() //将这次请求抛弃
			return
		}

		//如果验证通过，提取token
		tokenstring = tokenstring[7:]

		token, claims, err := common.ParseToken(tokenstring)

		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token无效或解析token错误！",
			})
			context.Abort() //将这次请求抛弃
			return
		}

		//验证通过获取claims中的userid
		//这里的userid是AdminUserId不要搞混了！
		userId := claims.UserId
		DB := common.GetDB()
		var user model.NewBeeAdminUser
		DB.First(&user, userId)

		//验证用户
		if user.AdminUserId == 0 {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "用户不存在！",
			})
			context.Abort() //将这次请求抛弃
			return
		}

		//用户存在将user信息写入上下文
		context.Set("adminUser", user)
		context.Next()
	}
}
